
import styled from 'styled-components';
import React, { CSSProperties, useEffect, useState } from 'react';
import { PlusOutlined, OrderedListOutlined } from '@ant-design/icons';
import { Button, Pagination, Drawer } from "antd";
import { useNavigate, useLocation } from "react-router-dom";

import { CategoryList, QiniuImage } from '../../components';
import { appstoreGetCategories, ApplicationCategory, appstoreGetApplicationByCategory, Application } from '../../services';

import { ApplicationUploader, MyApplicationsPage, ApplicationGrid } from './components';

export interface ApplicationStorePageProps {
    style?: CSSProperties;
    onChange?: () => Promise<void>;
}

export const ApplicationStorePage: React.FC<ApplicationStorePageProps> = (props) => {

    const [categories, setCategories] = useState<Array<ApplicationCategory>>([]);

    const [applications, setApplications] = useState<Array<Application>>([]);

    const [activeKey, setActiveKey] = useState<string | null>('1');

    const [loading, setLoading] = useState<boolean>(false);

    const [uploadOpen, setUploadOpen] = useState<boolean>(false);

    const [myListOpen, setMyListOpen] = useState<boolean>(false);

    const [pageSize, setPageSize] = useState<number>(20);

    const [page, setPage] = useState<number>(1);

    const [total, setTotal] = useState<number>(0);

    const navigate = useNavigate();

    useEffect(() => {
        // appstoreGetCategories
        appstoreGetCategories().then((data) => {
            setCategories(data);
        })
    }, []);

    const refresh = async (activeKey: string, page: number, pageSize: number) => {
        //
        setLoading(true);
        try {
            let res = await appstoreGetApplicationByCategory(parseInt(activeKey), page, pageSize);
            console.log(res);
            setApplications(res.data);
        } catch (error) {
            console.error(error);
        }
        setLoading(false);
    };
    //
    useEffect(() => {
        refresh(activeKey, page, pageSize);
    }, [activeKey, page, pageSize]);

    return (
        <Container style={props.style}>
            <Side>
                <CategoryList
                    style={{
                        flex: 1,
                        overflow: 'auto'
                    }}
                    items={categories.map((item, index) => {
                        return {
                            label: item.name,
                            key: item.code + '',
                            icon: item.icon && item.icon.length > 0 ? <QiniuImage style={{ width: '28px' }} src={item.icon}></QiniuImage> : <OrderedListOutlined></OrderedListOutlined>,
                        };
                    })}
                    activeKey={activeKey}
                    onChange={async (key, item) => {
                        setActiveKey(key);
                    }}
                    filter={false}
                ></CategoryList>
                <SideButtons>
                    <Button
                        loading={loading}
                        style={{ width: '80%', backgroundColor: '#07c160' }}
                        type={'primary'} danger
                        onClick={async () => {
                            setUploadOpen(true);
                        }}
                    >上传应用</Button>
                    <Button
                        loading={loading}
                        style={{ width: '80%' }}
                        onClick={async () => {
                            navigate('/apps/myapps');
                            // setMyListOpen(true);
                        }}
                    >我的应用</Button>
                </SideButtons>
            </Side>
            <Content>
                <Grid>
                    {
                        loading && (<></>)
                    }
                    {
                        !loading && (<ApplicationGrid items={applications} onInstalled={async (app) => {
                            props.onChange && await props.onChange();
                        }}></ApplicationGrid>)
                    }
                </Grid>
                {
                    total > pageSize && <Footer>
                        <Pagination
                            showSizeChanger={true}
                            defaultCurrent={page}
                            current={page}
                            pageSize={pageSize}
                            total={total}
                            onChange={(page, pageSize) => {
                                setPage(page);
                            }}
                            onShowSizeChange={(current, size) => {
                                setPageSize(size);
                            }}
                        ></Pagination>
                    </Footer>
                }
            </Content>
            <Drawer
                title="上传应用"
                onClose={() => {
                    setUploadOpen(false);
                }}
                width={'calc(100% - 220px)'}
                destroyOnClose={true}
                open={uploadOpen}>
                <ApplicationUploader categories={categories} onFinish={async () => {
                    //刷新
                    await refresh(activeKey, page, pageSize);
                    setUploadOpen(false);
                }}></ApplicationUploader>
            </Drawer>
            <Drawer
                title="我的应用"
                onClose={() => {
                    navigate('/myapps');
                    // setMyListOpen(false);
                }}
                width={'calc(100% - 220px)'}
                destroyOnClose={true}
                open={myListOpen}>
                <MyApplicationsPage categories={categories}></MyApplicationsPage>
            </Drawer>
        </Container>
    );
}

const Container = styled.div`
    height: 100%;
    width: 100%;
    display: flex;
    flex-direction: row;
    justify-content: center;
    align-items: center;
`;

const Side = styled.div`
    height: 100%;
    width: 160px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    align-items: center;
    border-right: 1px solid #DEDEDE;
`;

const SideButtons = styled.div`
    height: 100px;
    width: 100%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    gap: 10px;
`;

const Content = styled.div`
    flex:1;
    height: 100%;
    display: flex;
    flex-direction: column;
    align-items: flex-end;
`;
const Grid = styled.div`
    flex:1;
    width: 100%;
    overflow: auto;
`;

const Footer = styled.div`
    height: 48px;
    width: 100%;
    padding: 10px;
    background-color: #FFFFFF;
`;
